package com.itheima.dubbo.mysql.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.commons.pojo.entity.Log;
import com.itheima.commons.vo.backstage.PageResults;
import com.itheima.dubbo.interfaces.LogApi;
import com.itheima.dubbo.mysql.mapper.LoginLogMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author wds
 * @date 2021/12/19
 * @apiNote
 */
@Service
public class LogApiImpl implements LogApi {

    @Autowired
    private LoginLogMapper loginLogMapper;


    @Override
    public PageResults queryLogById(Long id, Integer page, Integer pagesize, String sortProp, String sortOrder) {
        LambdaQueryWrapper<Log> lambdaQuery = Wrappers.lambdaQuery(Log.class).eq(Log::getUserId, id);
        //查询当前用户登录的日志记录总数
        long count = loginLogMapper.selectCount(Wrappers.lambdaQuery(Log.class).eq(Log::getUserId, id));

        // 按照登录时间 排序
        // 1.升序
        if (sortOrder.equals("ascending") && sortProp.equals("logTime")) {
            lambdaQuery.orderByAsc(Log::getLogTime);
        } else {
            //2.降序
            lambdaQuery.orderByDesc(Log::getLogTime);
        }
        Page<Log> logPage = loginLogMapper.selectPage(new Page<>(page, pagesize), lambdaQuery);

        //获取到当前日志表记录集合                  （为什么会查到所有记录！！！！！！！！！！！）
        //进行筛选
        List<Log> logList = logPage.getRecords();
        for (Log log : logList) {
            //不是当前用户的记录就移除集合
            if (!log.getUserId().equals(id)) {
                logList.remove(log);
            }
        }

        List<?> totals = null;
        return new PageResults(page, pagesize, count, logList, totals);
    }
}
